# -*- coding:utf-8 -*-
import os,sys
import copy
import re
import traceback
import time
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, os.pardir))
import supeanut_config
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
from CommonLib.mylog import mylog
from BasicTool import BasicTool
from CommonLib.StockTool import StockTool
from CommonLib.db.MongoDBTool import MongoDBTool
from ExrightsTool import ExrightsTool


'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
	xxx
	xxxxx
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class SellStrategy:
	# init what
	def __init__(self):
		pass
	
	# 参数合理范围，[[min,max],step]
	# 区别整数为step数值
	def getParamRange(self, func_name):
		if func_name == "zhiYingSun":
			return {"MaxYingliPercent":[[0.1,0.3],0.1],"YingliHuiLuo":[[0.03,0.05],0.02],"zhiSun":[[0.04,0.08],0.02],\
					"holdday_max":[[5,20],5],"holdtoday":[[0,1],1]}

	# 基本的卖出策略，适用所用场合（必选）
	# 止盈止损策略,买卖均为收盘价
	# holdtoday=False：持股至今未卖的不计入结果
	# 返回sell_result[buyDatetime] = [sell_dateitime, "zhisun"], (holdtoday=True：[today，”hold“])
	def zhiYingSun(self, itemList, buyDatetime_list, MaxYingliPercent=0.2, YingliHuiLuo=0.05, zhiSun=0.08, holdday_max=3, holdtoday=0, period=[None,None]):
		if len(itemList) == 0:
			return {}
		period_start = itemList[0][0] if period[0] is None else period[0]
		period_end = itemList[-1][0] if period[1] is None else period[1]
		period_end_index = None
		if holdtoday == 0:
			holdtoday = False
		if holdtoday == 1:
			holdtoday = True
		# 记录买入周期点与itemIndex的map
		buyDatetime_itemIndex = {}
		item_index = 0
		for item in itemList:
			item_datetime = item[0]
			if item_datetime == period_end:
				period_end_index = item_index
			if item_datetime in buyDatetime_list:
				buyDatetime_itemIndex[item_datetime] = item_index
			item_index += 1
		if period_end_index is None:
			period_end_index = len(itemList)-1
			period_end = itemList[-1][0]
		# 遍历买点
		sell_result = {}
		for buyDatetime in buyDatetime_list:
			# period鉴别
			if buyDatetime < period_start or buyDatetime > period_end:
				continue
			item_index = buyDatetime_itemIndex[buyDatetime]
			# 收盘价作为买点
			buy_price = itemList[item_index][2]
			# 计算止盈止损
			holdday_count = -1
			close_max = buy_price
			sell_datetime = None
			zhiying_tag = False
			zhisun_tag = False
			holdday_reachMax = False
			sell_reason = "no confirm"
			for item in itemList[item_index: period_end_index+1]:
				holdday_count += 1
				cur_datetime = item[0]
				# 收盘价卖出
				cur_price = item[2]
				price_return = (cur_price - buy_price) / buy_price
				# 止损判断
				if price_return < -zhiSun:
					zhisun_tag = True
					sell_reason = "zhisun"
					sell_datetime = cur_datetime
					break
				# 止盈判断
				if close_max < cur_price:
					close_max = cur_price
				MaxYingliPercent_value = (close_max - buy_price) / buy_price 
				YingliHuiLuo_value = (close_max - cur_price) / close_max
				if MaxYingliPercent_value > MaxYingliPercent and YingliHuiLuo_value > YingliHuiLuo:
					zhiying_tag = True
					sell_reason = "zhiying"
					sell_datetime = cur_datetime
					break
				# 判断持股超出最长持有周期
				if holdday_count == holdday_max:
					holdday_reachMax = True
					sell_reason = "holdday_reachMax"
					sell_datetime = cur_datetime
					break
			# 持股至今
			if sell_datetime is None and holdtoday is True:
				sell_result[buyDatetime] = [itemList[period_end_index][0], "hold"]
			if sell_datetime is not None:
				sell_result[buyDatetime] = [sell_datetime, sell_reason]
		return sell_result



if __name__ == '__main__':
	obj = ExrightsTool()
	flag, itemList = obj.getAdjItemList("600000", "pre", "day")
	obj = SellStrategy()
	print obj.zhiYingSun(itemList, ["2014-03-10 00:00:00","2017-02-03 00:00:00"],0.2,0.05,0.08,30,True, ["2017-02-03 00:00:00","2017-09-09 00:00:00"])
